package com.wx.network.handler;

import com.wx.content.DataType;
import com.wx.network.codec.RpcProtocol;
import com.wx.network.handler.handlerInterface.RpcResponseOperate;
import com.wx.network.heartbeat.HeatBeatPackage;
import com.wx.network.mesg.Request;
import com.wx.network.mesg.Response;
import com.wx.util.IpUtil;
import com.wx.util.SerializationUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PingHeartBeatHandler implements RpcResponseOperate {
    private int port;
    public PingHeartBeatHandler(int port){
        this.port=port;
    }
    //处理心跳数据
    @Override
    public void handleData(ChannelHandlerContext channelHandlerContext, Request request) {
        HeatBeatPackage requestHeartBeat = request.getHeatBeatPackage();
        log.info("服务器收到客户端心跳：{}",requestHeartBeat);
        //发送数据
        Response response = new Response();
        HeatBeatPackage serverHeartBeat = new HeatBeatPackage();
        serverHeartBeat.setIp(IpUtil.getLocalIp());
        serverHeartBeat.setPort(port);
        response.setResult(serverHeartBeat);
        response.setDataType(DataType.PANG);
        //对于响应进行序列化
        byte[] bytes = SerializationUtil.serialzationObj(response);
        RpcProtocol protocol = new RpcProtocol();
        protocol.setLength(bytes.length);
        protocol.setData(bytes);
        //同步发送心跳数据
        channelHandlerContext.channel().writeAndFlush(protocol);
    }
}
